package com.android.activity;


import com.android.controler.RemoteControlSender;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class DeviceActivity extends Activity {
	private static final boolean DEBUG = true;
	private static final int REQUEST_ENABLE_BT = 1;
	private static final int REQUEST_CONNECT_BT = 2;
    private static final String TAG = "RCS.sender";
    public static final int ID_MSG = 1;
    public static final String MSG = "mensaje";
    private BluetoothAdapter mBluetoothAdapter = null;
    private RemoteControlSender mRCS = null;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.device);
        if(DEBUG) Log.e(TAG, "onCreate");

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
        	if(DEBUG) Log.e(TAG, getResources().getString(R.string.ERROR_NOT_SUPPORT_BLUETOOTH));
            Toast.makeText(this,getResources().getString(R.string.ERROR_NOT_SUPPORT_BLUETOOTH), Toast.LENGTH_LONG).show();
            finish();
            return;
            
        }
        
        /* 
        Button search = (Button) findViewById(R.id.lista_boton);
       
        search.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	startActivity(new Intent(DeviceActivity.this, RemoteControlActivity.class));
            }
        });*/
}
       
    @Override
    public void onStart() {
        super.onStart();
        if(DEBUG) Log.e(TAG, "onStart");

 
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (mRCS == null) runRCS();
        }
    }   
 
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case ID_MSG:
            	if(msg.arg1 == R.integer.RCS_IDLE){
            		//
            	}else if(msg.arg1 == R.integer.RCS_CONNECTING){
            		if(DEBUG) Log.e(TAG, getResources().getString(R.string.ID_MSG)+ getResources().getString(R.string.RCS_CONNECTING));
                    Toast.makeText(getApplicationContext(), msg.getData().getString(MSG)+ getResources().getString(R.string.RCS_CONNECTING),
                                   Toast.LENGTH_SHORT).show();
            	}else if(msg.arg1 == R.integer.RCS_CONNECTED){
            		if(DEBUG) Log.e(TAG, getResources().getString(R.string.ID_MSG)+ getResources().getString(R.string.RCS_CONNECTED));
                    Toast.makeText(getApplicationContext(), msg.getData().getString(MSG)+ getResources().getString(R.string.RCS_CONNECTED),
                                   Toast.LENGTH_SHORT).show();
            	}else if(msg.arg1 == R.integer.RCS_OUTPUT_STREAM){
            		if(DEBUG) Log.e(TAG, getResources().getString(R.string.ID_MSG)+ getResources().getString(R.string.RCS_OUTPUT_STREAM));
                    Toast.makeText(getApplicationContext(), msg.getData().getString(MSG)+ getResources().getString(R.string.RCS_OUTPUT_STREAM),
                                   Toast.LENGTH_SHORT).show();
            	}
                break;
            }
            }
        };
    private void runRCS() {
        Log.d(TAG, "runRCS");
        mRCS = new RemoteControlSender(this, mHandler);
    } 
    
    
    // Recoger resultados.
    public void onActivityResult(int requestCode, int resultCode, Intent i) {
        if(DEBUG) Log.d(TAG, "onActivityResult ");
        switch (requestCode) {
        //Dialogo de activacion de Bluetooth.
        // se regista en sender.onStart()
        case REQUEST_ENABLE_BT:
            if (resultCode == Activity.RESULT_OK) {
            	 if(DEBUG) Log.e(TAG, "ENABLE_BT OK");
                runRCS();
            } else {
            	 if(DEBUG) Log.e(TAG, "ENABLE_BT OK");
                finish();
            }
            break;
        // Resultado de intento de conexion BT.
            //se registra en sender.
        case REQUEST_CONNECT_BT:
            if (resultCode == Activity.RESULT_OK) {
                //Recoger la MAC y pedir la conexion a RCS.
            	if(DEBUG) Log.e(TAG, "CONNECT_BT OK");
            	String direccion = i.getExtras().getString(DeviceListActivity.DIRECCION);
            	BluetoothDevice bt = mBluetoothAdapter.getRemoteDevice(direccion);
            	mRCS.conecta(bt);
            	if(DEBUG) Log.e(TAG, "enviando id :"+R.integer.COMANDO_SIGUIENTE);
            	if(DEBUG) Log.e(TAG, "enviando valor :"+getResources().getInteger(R.integer.COMANDO_SIGUIENTE));
            	if(DEBUG) Log.e(TAG, "convertido a :"+Integer.toString(getResources().getInteger(R.integer.COMANDO_SIGUIENTE)).getBytes());
            	if(DEBUG) Log.e(TAG, "vuelta es :"+
            			+(new Integer(new String(Integer.toString(getResources().getInteger(R.integer.COMANDO_SIGUIENTE)).getBytes())).intValue()	)	
            	);
            	mRCS.write(Integer.toString(getResources().getInteger(R.integer.COMANDO_SIGUIENTE)).getBytes());
//            	mRCS.write("hola".getBytes());
            } else {if(resultCode== Activity.RESULT_CANCELED){
            	if(DEBUG) Log.e(TAG, "CONNECT_BT RESULT_CANCELED");
            }else{
            	if(DEBUG) Log.e(TAG, "CONNECT_BT ??");
            	  finish();
				}
			}
			break;
		}
    }  
    
    // Boton de Menu de Android
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_principal, menu);
        return true;
    }

    // Seleccion de dispositivo remoto y lanzar la conexion.
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
        	if(DEBUG) Log.e(TAG, "scan");
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_BT);
            return true;
        }
        return false;
    } 
}